/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.ucpaas.client;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Usage: RestClient
 *
 * @author Charkey
 * @date 2015/7/16 16:18
 */
public class RestClient {

    public static final String SYSTEM_CHARSET = "UTF-8";

    private CloseableHttpClient httpclient = null;

    private Map<String, Object> param = new HashMap<String, Object>();

    private String targetUrl = null;

    private RestClient() {
    }

    public static RestClient newClient() {
        RestClient restClient = new RestClient();
        restClient.httpclient = HttpClientBuilder.create().build();
        return restClient;
    }

    /**
     * post多参数，支持String值、String[]值
     */
    public static String post(String remoteUrl, Map<String, Object> paramMap) {
        return post(remoteUrl, paramMap, SYSTEM_CHARSET);
    }

    /**
     * post多参数，支持String值、String[]值
     */
    public static String post(String remoteUrl, Map<String, Object> paramMap, String responseCharset) {
        try {
            //构建post
            HttpPost httpPost = new HttpPost(new URL(remoteUrl).toURI());
            if (paramMap != null && paramMap.size() > 0) {   //post参数
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                for (String key : paramMap.keySet()) {
                    Object value = paramMap.get(key);
                    if (value instanceof Object[]) {    //数组值
                        Object[] texts = (Object[]) value;
                        for (Object text : texts) {
                            params.add(new BasicNameValuePair(key, text.toString()));
                        }
                    } else {
                        String text = value.toString();
                        params.add(new BasicNameValuePair(key, text));
                    }
                }
                httpPost.setEntity(new UrlEncodedFormEntity(params, responseCharset));
            }

            //执行post
            CloseableHttpClient httpclient = HttpClientBuilder.create().build();
            //          DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpResponse response = httpclient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() != 200) {
                throw new RuntimeException("HTTP request Exception");
            }
            return EntityUtils.toString(response.getEntity(), responseCharset);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public RestClient target(String url) {
        this.targetUrl = url;
        return this;
    }

    public RestClient param(String key, Object value) {
        param.put(key, value);
        return this;
    }

    public String post() {
        return post(targetUrl, param);
    }
}
